<?php
class channelAction extends commonAction {
    
    function __construct() {
        parent::__construct();
        helper('string');
    }
    
    //模型列表
    function index(){
        $channelM=D('Channel');
        $list=$channelM->field(true)->select();
        if($list===FALSE){
            if($channelM->getDbError()){
                $this->error($channelM->getDbError());
            }else{
                $this->error($channelM->getError());
            }
        }
        $this->assign("list",$list);
        $this->display();
    }
    
    //添加模型
    function add(){
        $channelM=D('Channel');
        if(!$this->isPost()){
            $this->display();
        }else{
            $step=I('post.step');
            //第一步入库,返回主键id
            $channelid = $channelM->addchannel(); 
            if (!$channelid) {
                $this->error($channelM->oneError());
            }
            //创建扩展表
            $addtable=I('post.addtable');
            if(empty($addtable) || (!empty($addtable) && !preg_match('/^[a-z][a-z0-9]+$/is',$addtable))){
                $addtable=C('DB_PREFIX').'addon'.$channelid;
            }else{
                $addtable=C('DB_PREFIX').$addtable;
            }
            $sql="create table `{$addtable}`
                (
                    `id` int unsigned not null auto_increment,
                    `aid` int unsigned not null,
                    primary key(`id`),
                    unique key `aid`(`aid`)
                )engine=innodb character set utf8 collate utf8_general_ci;
            ";
            if($channelM->execute($sql)===FALSE){
                $channelM->where('id='.$channelid)->delete();
                $this->error("创建表失败，请检查表{$addtable}是否已经存在");
            }else{
                $channelM_re=$channelM->where('id='.$channelid)->data(array("addtable"=>$addtable))->save();
                if(!$channelM_re){
                    $channelM->execute("drop table `{$addtable}`");
                    $channelM->where('id='.$channelid)->delete();
                }
            }
            $this->redirect("edit",array("id"=>$channelid));
        }
    }
    //编辑模型
    function edit(){
        $channelM=D('Channel');
        $id=I('id');
        if(empty($id) || !is_numeric($id)){
            $this->error('模型ID错误');
        }
        if(!$this->isPost()){
            $channel=$channelM->field(true)->find();
            if(!$channel){
                $this->error('模型不存在');
            }
            $channel['fieldset']=  unserialize($channel['fieldset']);
            $this->assign("channel",$channel);
            $this->display();
        }else{
            //修改fieldset
            $fieldsets=I('post.fieldset');
            $newfieldsetarr=array();
            foreach($fieldsets as $v){
                $vv=unserialize(htmlspecialchars_decode($v));//每个fieldset
                if(!$vv){
                    continue;
                }
                $newfieldsetarr[$vv['fieldname']]=$vv;
            }
            $newfieldset=serialize($newfieldsetarr);
            $channelM->where(array("id"=>$id))->data(array("fieldset"=>$newfieldset))->save();
            
            //全部修改成功
            $this->success('模型修改成功');
        }
    }
    
    //删除模型
    function delete(){
        $id=I('id');
        if(!$id || !is_numeric($id)){
            $this->error('模型ID不合法');
        }
        $channelM=D('Channel');
        $channel=$channelM->field(true)->where(array('id'=>$id))->find();
        if(!$channel){
            $this->error('模型不存在');
        }
        if($channel['channeltype']==1){
            $this->error('系统模型，禁止删除');
        }
        $addtable=$channel['addtable'];
        $re=$channelM->execute("drop table if exists `{$addtable}`");
        if($re!==FALSE){
            $re=$channelM->where(array('id'=>$id))->delete();
            if($re!==FALSE){
                $this->success('模型删除成功');
            }else{
                $this->error("删除模型记录失败");
            }
        }else{
            $this->error("删除扩展表{$addtable}失败");
        }
    }
    
    //添加字段
    function addfield(){
        $id=I('id');//获取模型id
        if(!$id || !is_numeric($id)){
            $this->error('模型ID不合法');
        }
        
        $channelM=D('Channel');///实例化模型
        $channel=$channelM->field(true)->where(array('id'=>$id))->find();//读取模型信息
        if(!$channel){
            $this->error('模型不存在');
        }
        if(!$this->isPost()){
            //非POST
            $this->assign('channel',$channel);
            //添加字段页面视图显示
            $this->display();
        }else{
            $postdata=I('post.');
            $postdata=array_map('strtolower',$postdata);//将所有值都转成小写
            
            //检测表单字段列表是否完整
            $requirearr=array('itemname','fieldname','itemtype','maxlength');//必须的字段验证数组
            foreach($requirearr as $var){
                if(empty($postdata[$var])){
                    $this->error($var.'不能为空');
                }
                if($var=='fieldname'){
                    if(!preg_match('/^[a-z][0-9a-z]+$/is', $postdata[$var])){
                        $this->error('字段名不合法，只允许数字和字母,并且以字母开头');
                    }
                }
            }
            
            //检测字段是否在主表和扩展表中已存在
            $exitfields=array();
            $mainfields_re=$channelM->query("show fields from `{$channel['maintable']}`");
            if($mainfields_re != FALSE){
                foreach($mainfields_re as $v){
                    $exitfields[strtolower($v['Field'])]=1;
                }
                unset($v);
            }
            $addfields_re=$channelM->query("show fields from `{$channel['addtable']}`");
            if($addfields_re != FALSE){
                foreach($addfields_re as $v){
                    if(!isset($exitfields[strtolower($v['Field'])])){
                        $exitfields[strtolower($v['Field'])]=1;
                    }
                }
                unset($v);
            }
            if(isset($exitfields[$postdata['fieldname']])){
                $this->error("字段名{$postdata['fieldname']}已在主表或扩展表中存在！");
            }
            //select,options,checkbox必须指定默认列表
            if (preg_match("#^(select|radio|checkbox)$#i", $postdata['itemtype'])) {
                if (!preg_match("#,#", $postdata['defaultvalue'])) {
                    $this->error("你设定了字段为 {$postdata['itemtype']} 类型，必须在默认值中指定元素列表，如：'a,b,c' ");
                }
            }
            
            //生成字段创建的sql
            $fieldsql=$this->_mkfieldinfo($postdata['itemtype'],$postdata['fieldname'],$postdata['defaultvalue'],$postdata['maxlength']);
            //尝试创建字段
            $re=$channelM->execute("alter table `{$channel['addtable']}` add {$fieldsql}");
            if($re===FALSE){
                $this->error('字段创建失败,sql错误:'.$channelM->getDbError());
            }
            
            //更新channel表fieldset字段
            $fieldset=$channel['fieldset'];
            $fieldinfo=array("itemname"=>$postdata['itemname'],"fieldname"=>$postdata['fieldname'],"itemtype"=>$postdata['itemtype'],"defaultvalue"=>$postdata['defaultvalue'],"needpage"=>$postdata['needpage'],"pagemark"=>$postdata['pagemark']);//字段信息
            if(empty($fieldset) || !unserialize($fieldset)){
                $fieldset[$postdata['fieldname']]=$fieldinfo;
            }else{
                $fieldset = unserialize($fieldset);
                $fieldset[$postdata['fieldname']]=$fieldinfo;
            }
            $newfieldset=serialize($fieldset);
            $channelM->where(array("id"=>$id))->data(array("fieldset"=>$newfieldset))->save();
            
            //创建成功，返回模型修改界面
            $this->success("添加字段成功",U("edit?id=".$id));
            
        }
    }
    //修改字段
    function editfield(){
        $id=I('id');//获取模型id
        $fieldname=I('fieldname');//字段名
        $channelM=D('Channel');//实例化模型
        $channel=$channelM->field(true)->where(array('id'=>$id))->find();//读取模型信息
        if(!$this->isPost()){
            $fieldset=unserialize($channel['fieldset']);
            $field=isset($fieldset[$fieldname])?$fieldset[$fieldname]:array();
            if(!$field){
                $this->error("字段不存在");
            }
            $this->assign("channel",$channel);
            $this->assign("field",$field);
            $this->display();
        }else{
            $fieldset=I('fieldset');
            if(empty($fieldset)){
                $this->error("提交的参数为空");
            }
            if(!isset($fieldset['itemname']) || empty($fieldset['itemname'])){
                $this->error("表单提示文字不能为空");
            }
            if(!isset($fieldset['fieldname']) || empty($fieldset['fieldname'])){
                $this->error("未指定字段名");
            }
            $oldfieldset=unserialize($channel['fieldset']);
            foreach($fieldset as $k=>$v){
                $oldfieldset[$fieldset['fieldname']][$k]=$v;
            }
            $re=$channelM->data(array("fieldset"=>serialize($oldfieldset)))->where(array("id"=>$id))->save();
            if($re===FALSE){
                $this->error($channelM->getDbError());
            }
            $this->success("字段修改成功");
        }
    }
    
    //生成字段创建语句
    function _mkfieldinfo($dtype,$fieldname,$dfvalue="",$mxlen=0){
        if(ACTION_NAME=='_mkfieldinfo'){
            exit;
        }
        $fieldinfo="";
        
        if ($dtype == "int") {
            if ($dfvalue == "" || preg_match("#[^0-9-]#", $dfvalue)) {
                $dfvalue = 0;
            }
            $fieldinfo = " `$fieldname` int(11) NOT NULL default '$dfvalue';";
        }elseif ($dtype == "float") {
            if ($dfvalue == "" || preg_match("#[^0-9\.-]#", $dfvalue)) {
                $dfvalue = 0;
            }
            $fieldinfo = " `$fieldname` float NOT NULL default '$dfvalue';";
        } else if ($dtype == "checkbox") {
            $dfvalue = str_replace(',', "','", $dfvalue);
            $dfvalue = "'" . $dfvalue . "'";
            $fieldinfo = " `$fieldname` SET($dfvalue) NULL;";
        }  else if ($dtype == "select" || $dtype == "radio") {
            $dfvalue = str_replace(',', "','", $dfvalue);
            $dfvalue = "'" . $dfvalue . "'";
            $fieldinfo = " `$fieldname` enum($dfvalue) NULL;";
        }  else if ($dtype == "textarea" || $dtype == "html") {
            $fieldinfo = " `$fieldname` mediumtext;";
        }  else {
            if (empty($dfvalue)) {
                $dfvalue = '';
            }
            if (empty($mxlen) || !is_numeric($mxlen)) {
                $mxlen = 100;
            }
            if ($mxlen > 255) {
                $mxlen = 250;
            }
            $fieldinfo = " `$fieldname` varchar($mxlen) NOT NULL default '$dfvalue';";
        }
        
        return $fieldinfo;
    }
}
